package dnl.jexem.cmd.remote;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import dnl.jexem.cmd.Command;
import dnl.jexem.cmd.CommandExecution;
import dnl.jexem.remote.ssh.SshCommandResult;
import dnl.jexem.remote.ssh.SshSession;

/**
 * Implements a <code>CommandExcecution</code> that excecutes on the local
 * machine.
 * 
 * @author Daniel Orr
 * 
 */
public class SshCommandExcecution extends CommandExecution {

	private SshCommandResult commandResult;
	//private long startTime;

	private SshSession sshSession;
	
	public SshCommandExcecution(SshSession sshSession, String... command) {
		super(command);
		this.sshSession = sshSession;
	}

	public SshCommandExcecution(SshSession sshSession, Command command) {
		super(command);
		this.sshSession = sshSession;
	}

	@Override
	public String getOutput() {
		if(commandResult == null)
			return "";
		return commandResult.getSysout();
	}

	@Override
	public String getErrorOutput() {
		if(commandResult == null)
			return "";
		return commandResult.getSyserr();
	}

	@Override
	public void executeCommand(long timeout, boolean block) {
		List<String> commandAndArgs = new ArrayList<String>();
		commandAndArgs.add(command.getCommand());
		commandAndArgs.addAll(Arrays.asList(command.getArgs()));

		try {
			commandResult = sshSession.executeCommand(getFullCommand());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void kill() {

	}
/*
	private class ControlThread extends Thread {
		private long timeout;
		private Process p;

		public ControlThread(long timeout, Process p) {
			this.timeout = timeout;
			this.p = p;
		}

		@Override
		public void run() {
			while (System.currentTimeMillis() - startTime < timeout) {
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			this.p.destroy();
		}
	}
*/
	@Override
	public String getAllOutputs() {
		StringBuilder sb = new StringBuilder();
		sb.append("Output:\n");
		sb.append(getOutput());
		sb.append("Error:\n");
		sb.append(getErrorOutput());
		sb.append("Exceptions:\n");
		for (String ex : exceptionMessages) {
			sb.append("_____________________________");
			sb.append(ex);
		}
		return sb.toString();
	}

}
